import cv2
import os
import json
from paddle.io import Dataset
import numpy as np

class handPointsDataset(Dataset):
    def __init__(self,path = "C:/Users/Administrator/Desktop/handC/image/"):
        self.data = [os.path.join(path,i) for i in os.listdir(path) if i[-4:]=="json"]

    def __getitem__(self, idx):
        i = self.data[idx]                       #json文件
        imgpath = i.replace("json","jpg")    #图片
        img = cv2.imread(imgpath)            #读取图片
        with open(i) as f:j = json.loads(f.read()) #读取标注文件
        
        x = img.transpose()
        x = x - 127.5
        x = x / 127.5
        y = j["shapes"][0]["points"]
        y = [y[0][0]/j["imageWidth"],y[0][1]/j["imageHeight"],y[1][0]/j["imageWidth"],y[1][1]/j["imageHeight"]]
        x = x.astype(np.float32)
        y = np.array(y,dtype=np.float32)
        
        return x,y
    
    def __len__(self):
        return len(self.data)
    

    def show(self,x,y):
        w,h = 640,480
        x = x * 127.5
        x = x + 127.5
        img = x.transpose()
        img = img.astype(np.uint8)
        
        img = cv2.circle(img, (int(y[0]*w),int(y[1]*h)), 3, (0,225,0), 1)
        img = cv2.circle(img, (int(y[2]*w),int(y[3]*h)), 3, (0,225,0), 1)
        cv2.imshow("windows",img)
        while(True):
         if cv2.waitKey(0)==97:
             break
        cv2.destroyAllWindows()


if __name__ == "__main__":
    dataset = handPointsDataset()
    x,y = dataset[0]
    dataset.show(x,y)